/**
* @CopyRight tstudy.com.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.community;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;

import uk.co.senab.photoview.PhotoView;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.BaseOnScrollListener;
import com.tstudy.laoshibang.base.BaseOnScrollListener.LoadMoreCallBack;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.CONSTANT.LoadType;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.community.CommentListAdapter.AdapterCallBack;
import com.tstudy.laoshibang.emojicon.EmojiconEditText;
import com.tstudy.laoshibang.emojicon.EmojiconsFragment;
import com.tstudy.laoshibang.emojicon.emoji.Emojicon;
import com.tstudy.laoshibang.event.CommentDeleteEvent;
import com.tstudy.laoshibang.event.CommunityCommentEvent;
import com.tstudy.laoshibang.event.CommunityLoveEvent;
import com.tstudy.laoshibang.login.LoginActivity;
import com.tstudy.laoshibang.mode.Comment;
import com.tstudy.laoshibang.mode.Community;
import com.tstudy.laoshibang.mode.Idxe;
import com.tstudy.laoshibang.mode.User;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.mode.response.CommentListResponse;
import com.tstudy.laoshibang.mode.response.CommunityDetailResponse;
import com.tstudy.laoshibang.mode.response.CreateCommentResponse;
import com.tstudy.laoshibang.profile.MyCommunityFragment;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;

import de.greenrobot.event.EventBus;
@SuppressLint({ "InflateParams", "CutPasteId" })
@SuppressWarnings({"unused"})
@EFragment(R.layout.comment_list)
public class CommunityDetailFragment extends BaseFragment{
	final static String TAG = "comment_list";
	public CommunityDetailFragment() {
		super();
	}
	
	@ViewById(R.id.comment_list_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.comment_list_progress)
	RelativeLayout mProgressLayout;
	
	@ViewById(R.id.comment_list_list)
	PullToRefreshListView mPullToRefreshListView;
	
	BaseOnScrollListener mBaseOnScrollListener;
	LoadType mLoadType;
	@ViewById(R.id.comment_list_comment_action)
	TextView mSendAction;
	@ViewById(R.id.comment_list_comment_ext)
	EmojiconEditText mCommentExt;

	@ViewById(R.id.comment_list_comment_emoji)
	ImageView mEmojiAction;
	
	@ViewById(R.id.comment_list_emoji_layout)
	RelativeLayout mEmojiLayout;
	
	boolean mIsFirstLoad = true;
	Handler mHandler;
	LayoutInflater mInflater;
	CommentListAdapter mCommentListAdapter;
	int mCurrentPosition = 0;
	List<View> mViewList = new ArrayList<View>();
	List<Comment> mComments = new ArrayList<Comment>();
	boolean mIsEmpty;
	@StringRes(R.string.community_detail_title)
	String mDefaultShareStr;
	int pageSize = 50;
	
	@StringRes(R.string.select_all)
	String mSelectAllStr;
	int mSelectAllKey = -1;
	int mCommunityId;
	String mUserNo;
	User mCommentToUser;
	int mCommentId;
	String mShareImg;
	boolean mkeyBordShow;
	boolean mIsComment;
	String mGroupId;
	int mPosition;

	public static void add(int containerViewId,int communityId,String userNo,boolean isComment,int position) {
		add(containerViewId, communityId, userNo, isComment, position,null);
	}
	public static void add(int containerViewId,int communityId,String userNo,boolean isComment,int position,String groupId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		args.putInt(CONSTANT.ARGS.COMMUNITY_ID, communityId);
		args.putBoolean(CONSTANT.ARGS.IS_COMMENT, isComment);
		args.putInt(CONSTANT.ARGS.POSITION, position);
		args.putString(CONSTANT.ARGS.USER_NO, userNo);
		args.putString(CONSTANT.ARGS.GROUP_ID, groupId);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,CommunityDetailFragment_.class.getName(),args);
		((BaseActivity) BaseApplication.mCurrentActivity).add(containerViewId, fragment, TAG);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		super.onCreate(savedInstanceState);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	int mHeightDifference;
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
	        mRootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
				@Override
				public void onGlobalLayout() {
					Rect r = new Rect();
					mRootLayout.getWindowVisibleDisplayFrame(r);
					int screenHeight = mRootLayout.getRootView().getHeight();
					mHeightDifference = screenHeight - (r.bottom - r.top);
					LogUtil.d("--screenHeight==" + screenHeight + ",r.bottom==" + r.bottom + ",r.top==" + r.top + ",softheight==" + mHeightDifference );
					if (mHeightDifference > BaseApplication.mStatusBarHeight) {
						mkeyBordShow = true;
						mEmojiAction.setImageResource(R.drawable.expression);
						mEmojiLayout.setVisibility(View.GONE);
//						mRootLayout.scrollTo(0, mHeightDifference-BaseApplication.mStatusBarHeight);
					}else{
//						LogUtil.d("mHeightDifference==" + mHeightDifference );
//						mRootLayout.scrollTo(0, 0);
						if (mkeyBordShow) {
							mEmojiAction.setImageResource(R.drawable.keyboard);
						}
						mkeyBordShow = false;
					}
				}
			});
			initHeaderView();
			mCommentListAdapter = new CommentListAdapter();
			mPullToRefreshListView.setAdapter(mCommentListAdapter);
			mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
			mCommentListAdapter.setAdatperCallBack(new AdapterCallBack() {
				@Override
				public void onAvatarClick(String userNo) {
//					UserCommunityFragment.add(userNo, mFragmentId);
					MyCommunityFragment.add(mFragmentId, userNo, mGroupId);
				}

				@Override
				public void onDeleteClick(int commentId, int position) {
					String title = BaseApplication.getResString(R.string.delete_comment_dialog_title);
					String content = BaseApplication.getResString(R.string.delete_comment_dialog_content);
					showDeleteCommentDialog(commentId,position,title, content);
				}

				@Override
				public void onCommentClick(User fromUser,Comment comment,int position) {
					if (comment != null && (comment.isDel == 1)) {
						mCommentId = 0;
						mCommentToUser = null;
						mCommentExt.setHint(R.string.community_detail_comment_hint);
					}else{
						mCommentExt.setHint("@"+ fromUser.nick);
						mCommentToUser = fromUser;
						mHandler.postDelayed(new Runnable() {
							
							@Override
							public void run() {
								showSoftKeyBoard(mCommentExt, true);
							}
						}, 500);
					}
				}
			});
			mPullToRefreshListView.getRefreshableView().addHeaderView(mHeaderLayout);
			mLoadType = LoadType.load_first;
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					getCommunityDetail();
					if (mIsComment) {
						mCommentExt.setFocusableInTouchMode(true);
				        mCommentExt.requestFocus();
					}
				}
			}, CONSTANT.LOAD_DATA_DELAY_TIME);
			mBaseOnScrollListener = new BaseOnScrollListener(new LoadMoreCallBack() {
				@Override
				public void loadMore() {
					if (mComments.size() >= pageSize) {
						mPullToRefreshListView.startLoadMore();
						mLoadType = LoadType.load_more;
						getCommentList();
					}
				}
			});
			mPullToRefreshListView.setOnScrollListener(mBaseOnScrollListener);
			mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
				@Override
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					getCommunityDetail();
				}
			});
		}
	}
	RelativeLayout mHeaderLayout;
	ImageView mUserAvatar;
	TextView mUserName;
	TextView mCreateTime;
	TextView mAddress;
	TextView mTitle;
//	WebView mContent;
	TextView mContent;
	RelativeLayout mImgLayout;
	TextView mCommentTxt;
	TextView mLoveTxt;
	TextView mShareTxt;
	TextView mDeleteAction;
	ImageView mCommentIcon;
	ImageView mLoveIcon;
	ImageView mShareIcon;
	RelativeLayout mCommentLayout;
	RelativeLayout mLoveLayout;
	RelativeLayout mShareLayout;
	
	public void initHeaderView(){
		mHeaderLayout = (RelativeLayout) mInflater.inflate(R.layout.community_detail_header, null);
		mUserAvatar = (ImageView)mHeaderLayout.findViewById(R.id.community_detail_header_user_avatar);
		mUserName = (TextView)mHeaderLayout.findViewById(R.id.community_detail_header_user_name);
		mCreateTime = (TextView)mHeaderLayout.findViewById(R.id.community_detail_header_create_time);
		mContent = (TextView) mHeaderLayout.findViewById(R.id.community_detail_header_content);
//		mContent = (WebView) mHeaderLayout.findViewById(R.id.community_detail_header_content);
		mAddress = (TextView) mHeaderLayout.findViewById(R.id.community_detail_header_address);
		mImgLayout = (RelativeLayout) mHeaderLayout.findViewById(R.id.community_detail_header_img_layout);
		mCommentTxt = (TextView) mHeaderLayout.findViewById(R.id.community_detail_header_action_comment_txt);
		mLoveTxt = (TextView) mHeaderLayout.findViewById(R.id.community_detail_header_action_love_txt);
		mShareTxt = (TextView) mHeaderLayout.findViewById(R.id.community_detail_header_action_share_txt);
		mCommentIcon = (ImageView) mHeaderLayout.findViewById(R.id.community_detail_header_action_comment_icon);
		mLoveIcon = (ImageView) mHeaderLayout.findViewById(R.id.community_detail_header_action_love_icon);
		mShareIcon = (ImageView) mHeaderLayout.findViewById(R.id.community_detail_header_action_share_icon);
		mCommentLayout = (RelativeLayout) mHeaderLayout.findViewById(R.id.community_detail_header_action_comment_click);
		mLoveLayout = (RelativeLayout) mHeaderLayout.findViewById(R.id.community_detail_header_action_love_click);
		mShareLayout = (RelativeLayout) mHeaderLayout.findViewById(R.id.community_detail_header_action_share_click);
		mDeleteAction = (TextView) mHeaderLayout.findViewById(R.id.community_detail_header_delete);
	
	}
	Community mCommunity;
	public void setHeaderView(){
		if (mCommunity != null) {
//			mContent.loadData(mCommunity.content, "text/html; charset=UTF-8", null);
			mContent.setText(mCommunity.content);
			mCommentTxt.setText(mCommunity.evalNum + "");
			mLoveTxt.setText(mCommunity.praiseNum + "");
			if (TextUtils.isEmpty(mCommunity.provinceName) || TextUtils.isEmpty(mCommunity.cityName)) {
				mAddress.setVisibility(View.GONE);
			}else{
				mAddress.setVisibility(View.VISIBLE);
				mAddress.setText(mCommunity.provinceName + " " + mCommunity.cityName);
			}
			if (!TextUtils.isEmpty(mCommunity.createTime)) {
				mCreateTime.setText(CommonUtil.timelineDateStr(Long.parseLong(mCommunity.createTime)));
			}
			if (mCommunity.isAnous.key==1) {
				mUserAvatar.setImageResource(R.drawable.anonymous_head);
			}else{
				HttpManager.getInstance().loadEditAvatar(mUserAvatar,mCommunity.user.imgIdxName,R.drawable.profile_avatar_default);
			}
			if (mCommunity.type.key == CONSTANT.COMMUNITY_TYPE_OFFICIAL) {
				mUserAvatar.setImageResource(R.drawable.logo);
				mUserName.setText(R.string.app_name);
			}else{
				mUserName.setText(mCommunity.user.nick);
			}
			mLoveIcon.setSelected(mCommunity.isPraise==1);
			mCommentLayout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mCommentId = 0;
					mCommentToUser = null;
					mCommentExt.setHint(R.string.community_detail_comment_hint);
				}
			});
			mLoveLayout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (BaseApplication.checkLogin()) {
						mCommunity.isPraise = mCommunity.isPraise==1?0:1;
						mLoveIcon.setSelected(mCommunity.isPraise == 1);
						mCommunity.praiseNum = mCommunity.isPraise == 1?mCommunity.praiseNum+1:mCommunity.praiseNum-1;
						mLoveTxt.setText(mCommunity.praiseNum+"");
						CommonUtil.loveAnimator(mLoveIcon);
						loveAction(mCommunity,CONSTANT.ASSO_TYPE_COMMUNITY, mCommunity.isPraise==1?CONSTANT.LOVE_ACTION:CONSTANT.UNLOVE_ACTION);
					}else{
						LoginActivity.show();
					}
				}
			});
			mShareLayout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
//					showShareDialog();
					share(mCommunity);
				}
			});
			if (mCommunity.isDel==1) {
				mDeleteAction.setVisibility(View.VISIBLE);
				mDeleteAction.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						String title = BaseApplication.getResString(R.string.delete_community_dialog_title);
						String content = BaseApplication.getResString(R.string.delete_community_dialog_content);
						showDeleteCommunityDialog(title, content);
					}
				});
			}
			fillImgLayout(mImgLayout, mCommunity);
			
		}
	}
	
	final int COLUMN_SIZE = 3;
	int photoMargin = CommonUtil.dip2px(5);
	int layoutMargin = CommonUtil.dip2px(60);
	int mBigImgWidth = BaseApplication.mScreenWidth - layoutMargin;
	int mBigImgHeigh = mBigImgWidth*2/3;
	int  mImageWidth = (BaseApplication.mScreenWidth -photoMargin*4-layoutMargin)/COLUMN_SIZE;
	int mImageHeight = mImageWidth;
	public void fillImgLayout(final RelativeLayout layout,final Community community) {
		layout.removeAllViews();
		int size = community.idxes.size();
		int displaySize = Math.min(9, size);
		for (int i = 0; i < displaySize; i++) {
			ImageView imgView = new ImageView(BaseApplication.mContext);
			imgView.setId(i + 1);
			RelativeLayout.LayoutParams imgLp = new RelativeLayout.LayoutParams(mImageWidth, mImageHeight);
			if (displaySize ==1) {
				imgLp.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
				imgLp.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
				imgView.setScaleType(ScaleType.FIT_START);
				imgView.setAdjustViewBounds(true);
			}else{
				imgView.setScaleType(ScaleType.CENTER_CROP);
			}
			int rowIndex = i/COLUMN_SIZE;
			int columnIndex = i%COLUMN_SIZE;
			if (rowIndex != 0) {
				imgLp.addRule(RelativeLayout.BELOW,i-COLUMN_SIZE+1);
			}
			if (columnIndex != 0) {
				imgLp.setMargins(0, 0,photoMargin, photoMargin);
				imgLp.addRule(RelativeLayout.RIGHT_OF, i);
			}else{
				imgLp.setMargins(photoMargin, 0, photoMargin, photoMargin);
			}
			layout.addView(imgView, imgLp);
			layout.getLayoutParams().height = RelativeLayout.LayoutParams.WRAP_CONTENT;
			if (displaySize ==1) {
				HttpManager.getInstance().loadCommonImage(imgView,community.idxes.get(i).imgIdxName);
			}else{
				HttpManager.getInstance().loadCommonImage(imgView,community.idxes.get(i).imgIdxName + CommonUtil.buildCropUrl(imgLp.width, imgLp.height));
			}
			final int picIndex = i;
			imgView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					showPictureDialog(community,picIndex);
				}
			});
		}
	}
	
	Dialog mPicDialog;
	ViewPager mViewPager;
	RelativeLayout mLoadingLayout;
	ImageView mDownloadView;
	LinearLayout mLinearLayout;
	ListItemPageAdapter mPageAdapter;
	public void showPictureDialog(Community community,int position){
		RelativeLayout pictureLayout = (RelativeLayout) mInflater.inflate(R.layout.picture_view, null);
		if(mPicDialog != null && mPicDialog.isShowing()){
			return;
		}
		mPicDialog = new Dialog(BaseApplication.mCurrentActivity, R.style.fullscreendialog);
		mPicDialog.setCanceledOnTouchOutside(true);
		mPicDialog.setContentView(pictureLayout);
		mLinearLayout = (LinearLayout) pictureLayout.findViewById(R.id.picture_view_select_layout);
		mViewPager = (ViewPager)pictureLayout.findViewById(R.id.picture_view_viewpage);
		mLoadingLayout = (RelativeLayout)pictureLayout.findViewById(R.id.picture_view_progress);
		mDownloadView = (ImageView)pictureLayout.findViewById(R.id.picture_view_download);
		mDownloadView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mViewList.get(mCurrentPosition).buildDrawingCache();
				String filePath = CommonUtil.saveImageToGallery(BaseApplication.mContext, mViewList.get(mCurrentPosition).getDrawingCache());
				BaseApplication.showToast(BaseApplication.getResString(R.string.save_file_path) + filePath);
			}
		});
		mPageAdapter = new ListItemPageAdapter();
		mViewPager.setAdapter(mPageAdapter);
		mViewPager.setOnPageChangeListener(mPageAdapter);
		fillPictures(community.idxes, position);
		Window window = mPicDialog.getWindow();
		window.setBackgroundDrawable(new ColorDrawable(0x00000000));
		window.setLayout(BaseApplication.mScreenWidth, BaseApplication.mScreenHeight);
		window.setGravity(Gravity.CENTER);
//		window.setWindowAnimations(R.style.look_share_show);
		window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
				| WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		mPicDialog.show();
//		mHandler.postDelayed(new Runnable() {
//			@Override
//			public void run() {
//				showSoftKeyBoard(searchExt, true);
//			}
//		}, CONSTANT.LOAD_DATA_DELAY_TIME);
	}
	
	class ListItemPageAdapter extends PagerAdapter implements OnPageChangeListener{
		List<View> mViewList = new ArrayList<View>();
		public void setData(List<View> viewList){
			mViewList = viewList;
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return mViewList.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
		
		 @Override  
		    public void destroyItem(ViewGroup container, int position,Object object) {  
		        container.removeView(mViewList.get(position));  

		    }  

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(mViewList.get(position));
			return mViewList.get(position);
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onPageSelected(int position) {
			changeSelectBg(position);
			
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			// TODO Auto-generated method stub
		}
		
	}

	public void changeSelectBg(int position){
			if (mLinearLayout != null) {
				mLinearLayout.getChildAt(position).setSelected(true);
				mCurrentPosition = position;
				int childCount = mLinearLayout.getChildCount();
				for (int i = 0; i < childCount; i++) {
					mLinearLayout.getChildAt(i).setSelected(i==position);
				}
			}
	} 
	public void fillPictures(List<Idxe> idxe,int position){
		mViewList.clear();
		mLinearLayout.removeAllViews();
		long begin = System.currentTimeMillis();
		int size = idxe.size();
		mLoadingLayout.setVisibility(View.VISIBLE);
		for (int i = 0; i < size; i++) {
			final Idxe each = idxe.get(i);
			final PhotoView image = new PhotoView(BaseApplication.mContext);
			HttpManager.getInstance().loadCommonImage(image, each.imgIdxName,new ImageLoadingListener() {
				@Override
				public void onLoadingStarted(String imageUri, View view) {
					// TODO Auto-generated method stub
				}
				
				@Override
				public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
					// TODO Auto-generated method stub
					mLoadingLayout.setVisibility(View.GONE);
				}
				
				@Override
				public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
					// TODO Auto-generated method stub
					mLoadingLayout.setVisibility(View.GONE);
				}
				
				@Override
				public void onLoadingCancelled(String imageUri, View view) {
					// TODO Auto-generated method stub
					mLoadingLayout.setVisibility(View.GONE);
				}
			});
			mViewList.add(image);
			image.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mPicDialog.dismiss();
				}
			});
			if (size > 1) {
				fillSelectLayout(mLinearLayout, i);
			}
		}
		mPageAdapter.setData(mViewList);
		mViewPager.setCurrentItem(position);
	}
	int mIndexMargin = CommonUtil.dip2px(6);
	public void fillSelectLayout(LinearLayout layout,int position){
		ImageView image = new ImageView(BaseApplication.mContext);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
		lp.setMargins(mIndexMargin, 0, mIndexMargin, 0);
		image.setImageResource(R.drawable.homepage_pager_selector);
		if (position == 0) {
			image.setSelected(true);
		}
		layout.addView(image, lp);
	}
	
	public void share(Community community){
		String mDefaultShareStr = BaseApplication.getResString(R.string.community_list_title);
		String mShareImg = "";
		if (community.idxes != null && community.idxes.size() > 0) {
			mShareImg = community.idxes.get(0).imgIdxName;
		}
		if(mShareDialog == null){
			mDialogView = (LinearLayout) mInflater.inflate(R.layout.share_pop, null);
			mShareDialog = buildAlertDialog(mDialogView,CommonUtil.dip2px(20));
		}
		if (mShareDialog.isShowing()) {
			return;
		}
		String title = TextUtils.isEmpty(community.title)?community.content:community.title;
		final String content = TextUtils.isEmpty(community.content)?mDefaultShareStr:community.content;
		if (TextUtils.isEmpty(title)) {
			title = mDefaultShareStr;
		}
		if (TextUtils.isEmpty(mShareImg) && community.isAnous.key == 0) {
			mShareImg = community.user.imgIdxName;
		}
		CommonUtil.showShareDialog(CONSTANT.ASSO_TYPE_COMMUNITY, mDialogView,mShareDialog, mInflater, mShareImg, title, content,community.shareUrl);
	}
	Dialog mShareDialog;
	LinearLayout mDialogView;
	
	@Click(R.id.comment_list_back)
	public void back(){
		backAction(mFragmentId);
	}
	
	@Click(R.id.comment_list_comment_action)
	public void commentAction(){
		if (isShowInput()) {
			if (mkeyBordShow) {
				showSoftKeyBoard(mCommentExt, false);
			}else{
				mEmojiAction.setImageResource(R.drawable.expression);
				mEmojiLayout.setVisibility(View.GONE);
			}
		}
		if (!BaseApplication.checkLogin()) {
//			LoginFragment.add(mFragmentId, null);
			LoginActivity.show();
			return;
		}
		if (TextUtils.isEmpty(mCommentExt.getText())) {
			BaseApplication.showToast(R.string.comment_content_not_null);
			return;
		}
		createComment(mCommentExt.getText().toString(), mCommentToUser != null ?mCommentToUser.userNo:"");
	}
	@Click(R.id.comment_list_comment_emoji)
	public void showEmojiLayout(){
//		showEmojiDialog();
		if (mHeightDifference> BaseApplication.mStatusBarHeight) {
			mEmojiLayout.getLayoutParams().height = mHeightDifference-BaseApplication.mStatusBarHeight;
		}
		//显示键盘
		if (mEmojiLayout.getVisibility() == View.VISIBLE) {
			mEmojiAction.setImageResource(R.drawable.expression);
			mEmojiLayout.setVisibility(View.GONE);
			mHandler.postDelayed(new Runnable() {
				public void run() {
					showSoftKeyBoard(mCommentExt, true);
				}
			},100);
		}else{//显示表情
			mEmojiAction.setImageResource(R.drawable.keyboard);
			showSoftKeyBoard(mCommentExt, false);
			getChildFragmentManager()
	        .beginTransaction()
	        .replace(R.id.comment_list_emoji_layout, EmojiconsFragment.newInstance(false))
	        .commit();
			mHandler.postDelayed(new Runnable() {
				public void run() {
					mEmojiLayout.setVisibility(View.VISIBLE);
					mEmojiLayout.startAnimation(AnimationUtils.loadAnimation(BaseApplication.mContext, R.anim.slide_in_from_bottom));
				}
			},100);
		}
	}
	
	
	Dialog mEmojiDialog;
	public void showEmojiDialog(){
		RelativeLayout imojiLayout = (RelativeLayout) mInflater.inflate(R.layout.emoji_dialog, null);
		if(mEmojiDialog != null && mEmojiDialog.isShowing()){
			return;
		}
		mEmojiDialog = new Dialog(BaseApplication.mCurrentActivity, 0);
		mEmojiDialog.setCanceledOnTouchOutside(true);
		mEmojiDialog.setContentView(imojiLayout);
		RelativeLayout emojiLayout = (RelativeLayout) imojiLayout.findViewById(R.id.emoji_dialog_comment_layout);
		ImageView emoji = (ImageView) imojiLayout.findViewById(R.id.emoji_dialog_comment_emoji);
		TextView comment = (TextView) imojiLayout.findViewById(R.id.emoji_dialog_comment_action);
		emoji.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mEmojiDialog.dismiss();
			}
		});
//		mPageAdapter = new ListItemPageAdapter();
//		mViewPager.setAdapter(mPageAdapter);
//		mViewPager.setOnPageChangeListener(mPageAdapter);
		Window window = mEmojiDialog.getWindow();
//		window.setBackgroundDrawable(new ColorDrawable(0x00000000));
		window.setLayout(BaseApplication.mScreenWidth, CommonUtil.dip2px(310));
		window.setGravity(Gravity.BOTTOM);
//		window.setWindowAnimations(R.style.look_share_show);
		window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
				| WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		mEmojiDialog.show();
//		mHandler.postDelayed(new Runnable() {
//			@Override
//			public void run() {
//				showSoftKeyBoard(searchExt, true);
//			}
//		}, CONSTANT.LOAD_DATA_DELAY_TIME);
	}
	
	
	
	
	
//	public static void loveAnimator(View view){
//	       AnimatorSet animatorSet = new AnimatorSet();  
//	       ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX",1f,2f);  
//	       scaleX.setDuration(200);  
//	       ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f,2f);  
//	       scaleY.setDuration(200); 
//	       ObjectAnimator scaleXN = ObjectAnimator.ofFloat(view, "scaleX",2f,1.0f);  
//	       scaleX.setDuration(200);  
//	       ObjectAnimator scaleYN = ObjectAnimator.ofFloat(view, "scaleY",2f,1.0f);  
//	       scaleY.setDuration(200); 
//	       animatorSet.play(scaleXN).with(scaleYN);
//	       animatorSet.play(scaleX).with(scaleY);
//	       animatorSet.start();  
//	} 
	Dialog mDeleteDialog;
	@SuppressLint("InflateParams")
	public void showDeleteCommunityDialog(String title,String content){
		RelativeLayout dialogView = (RelativeLayout) mInflater.inflate(R.layout.common_alert_dialog, null);
		if(mDeleteDialog != null && mDeleteDialog.isShowing()){
			return;
		}
		mDeleteDialog = buildAlertDialog(dialogView,CommonUtil.dip2px(80));
		TextView titleTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_title);
		final TextView contentTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_content);
		TextView cancelTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_cancel);
		TextView confirmTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_confirm);
		confirmTxt.setText(R.string.common_delete);
		titleTxt.setText(title);
		contentTxt.setText(content);
		confirmTxt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mDeleteDialog.dismiss();
				deleteCommunity();
			}
		});
		cancelTxt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mDeleteDialog.dismiss();
			}
		});
		mDeleteDialog.show();
	}
	
	Dialog mDeleteCommentDialog;
	@SuppressLint("InflateParams")
	public void showDeleteCommentDialog(final int commentId,final int position,String title,String content){
		RelativeLayout dialogView = (RelativeLayout) mInflater.inflate(R.layout.common_alert_dialog, null);
		if(mDeleteCommentDialog != null && mDeleteCommentDialog.isShowing()){
			return;
		}
		mDeleteCommentDialog = buildAlertDialog(dialogView,CommonUtil.dip2px(80));
		TextView titleTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_title);
		final TextView contentTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_content);
		TextView cancelTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_cancel);
		TextView confirmTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_confirm);
		confirmTxt.setText(R.string.common_delete);
		titleTxt.setText(title);
		contentTxt.setText(content);
		confirmTxt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mDeleteCommentDialog.dismiss();
				deleteComment(commentId,position);
			}
		});
		cancelTxt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mDeleteCommentDialog.dismiss();
			}
		});
		mDeleteCommentDialog.show();
	}
	
	/**
	 * 吐槽点赞
	 * @param activeId
	 * @param type
	 * @param isPraise
	 */
	private void loveAction(final Community community,int type,final int isPraise){
		BaseListJsonHandler<BaseResponse> response = new BaseListJsonHandler<BaseResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (mPosition >= 0) {
						CommunityLoveEvent event = new CommunityLoveEvent();
						event.isPrised = isPraise;
						event.position = mPosition;
						EventBus.getDefault().post(event);
					}
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					BaseResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().loveAction(BaseApplication.mUserNo, type, community.tcId, isPraise,mGroupId, response);
	}
	
	

	private void getCommentList(){
		if (mIsLoading) {
			return ;
		}
		if (mIsEmpty) {
			start = 0;
		}else{
			start = mComments.size();
		}
		if (mLoadType == LoadType.load_more) {
			limit = pageSize;
		}else if (mLoadType == LoadType.load_refresh){
			limit = 1;
		}
		mIsLoading = true;
		BaseListJsonHandler<CommentListResponse> response = new BaseListJsonHandler<CommentListResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, CommentListResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (mIsEmpty) {
						mComments.clear();
					}
					if (response.getData() != null) {
						List<Comment> list = response.getData().getList();
						if (list != null && list.size() > 0) {
							mComments.addAll(list);
							mIsEmpty = false;
						}
					}
					if (mLoadType == LoadType.load_more) {
						if (mComments.size() == response.getData().getCount() || response.getData().getCount() == 0) {
							mBaseOnScrollListener.mIsEnd = true;
						}else{
							mBaseOnScrollListener.mIsEnd = false;
						}
					}else{
						mBaseOnScrollListener.mIsEnd = false;
					}
					mCommentListAdapter.setData(mComments);
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					CommentListResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected CommentListResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,CommentListResponse.class);
			}
		};
		HttpManager.getInstance().getCommentList(BaseApplication.mUserNo, mCommunityId,start,limit,null,null,response);
		limit = pageSize;
	}
	
	private void getCommunityDetail(){
		BaseListJsonHandler<CommunityDetailResponse> response = new BaseListJsonHandler<CommunityDetailResponse>() {
			public void onStart() {
				if (mLoadType == LoadType.load_first) {
					showProgressBar(mProgressLayout);
				}
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, CommunityDetailResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (response.getData() != null) {
						mCommunity = response.getData();
						mComments.clear();
						List<Comment> list = mCommunity.comments;
						LogUtil.d("---detail comment list size" + list.size());
						if (list != null) {
							mComments.addAll(list);
						}
						if (mComments == null || mComments.size() == 0) {
							mIsEmpty = true;
							mComments.add(new Comment());
						}else{
							mIsEmpty = false;
						}
						mCommentListAdapter.setData(mComments);
						setHeaderView();
					}
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					CommunityDetailResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected CommunityDetailResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,CommunityDetailResponse.class);
			}
		};
		HttpManager.getInstance().getCommunityDetail(BaseApplication.mUserNo, mCommunityId, mGroupId,response);
	}
	
	private void deleteCommunity(){
		BaseListJsonHandler<BaseResponse> response = new BaseListJsonHandler<BaseResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					backAction(mFragmentId);
					EventBus.getDefault().post("");
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					BaseResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().deleteCommunity(BaseApplication.mUserNo, mCommunityId, mGroupId, response);
	}
	boolean isCreateing;
	private void createComment(String content,String toUserNo){
		if (isCreateing) {
			return;
		}
		isCreateing = true;
		BaseListJsonHandler<CreateCommentResponse> response = new BaseListJsonHandler<CreateCommentResponse>() {
			public void onStart() {
				if (mLoadType == LoadType.load_first) {
//					showProgressBar(mProgressLayout);
				}
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, CreateCommentResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					mCommunity.evalNum++;
					int count = mCommunity.evalNum;
					mCommentTxt.setText(count + "");
					mCommentExt.setText("");
					BaseApplication.showToast("评论成功");
					if (mComments.size() == start + limit) {
						mLoadType = LoadType.load_more;
					}else{
						mLoadType = LoadType.load_refresh;
					}
					getCommentList();
					if (mPosition >= 0) {
						CommunityCommentEvent event = new CommunityCommentEvent();
						event.position = mPosition;
						EventBus.getDefault().post(event);
					}
				}else{
					BaseApplication.showToast(response.getErrMsg());
				}
//				afterLoading();
				isCreateing = false;
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					CreateCommentResponse errorResponse) {
				isCreateing = false;
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected CreateCommentResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,CreateCommentResponse.class);
			}
		};
		HttpManager.getInstance().createComment(BaseApplication.mUserNo, toUserNo, mCommunityId, mCommentId,content, mGroupId,response);
	}
	private void deleteComment(int commentId,final int position){
		BaseListJsonHandler<BaseResponse> response = new BaseListJsonHandler<BaseResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					mCommunity.evalNum--;
					int count = mCommunity.evalNum;
					mCommentTxt.setText(count + "");
					mComments.remove(position);
					mCommentListAdapter.setData(mComments);
					int selection = Math.min(position, mComments.size());
					if (selection != 0) {
						mPullToRefreshListView.getRefreshableView().setSelection(position);
					}
					CommentDeleteEvent event = new CommentDeleteEvent();
					event.position = mPosition;
					EventBus.getDefault().post(event);
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					BaseResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().deleteComment(BaseApplication.mUserNo, commentId,mGroupId, response);
	}

	public void afterLoading(){
		mIsLoading = false;
		hideProgressBar(mProgressLayout);
		if(mLoadType == LoadType.load_more){
			if (mBaseOnScrollListener.mIsEnd) {
				mPullToRefreshListView.endLoadMore(BaseApplication.getResString(R.string.comment_no_more_data));
			}else{
				mPullToRefreshListView.stopLoadMore();
			}
		}
		if(mPullToRefreshListView != null){
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if(mPullToRefreshListView != null){
						mPullToRefreshListView.onRefreshComplete();
						LogUtil.d("--onRefreshComplete afterloading");
					}
				}
			}, 1000);
		}
	}
	@Override
	public void clear() {
		mEmojiLayout.setVisibility(View.GONE);
		showSoftKeyBoard(mCommentExt, false);
	}
	
	public boolean isShowInput(){
		return mkeyBordShow || mEmojiLayout.getVisibility() == View.VISIBLE;
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
			mCommunityId = args.getInt(CONSTANT.ARGS.COMMUNITY_ID);
			mUserNo = args.getString(CONSTANT.ARGS.USER_NO);
			mIsComment = args.getBoolean(CONSTANT.ARGS.IS_COMMENT);
			mPosition = args.getInt(CONSTANT.ARGS.POSITION);
			mGroupId = args.getString(CONSTANT.ARGS.GROUP_ID);
		}
	}
	public void onEmojiconBackspaceClicked(View v) {
		EmojiconsFragment.backspace(mCommentExt);
		
	}
	public void onEmojiconClicked(Emojicon emojicon) {
		EmojiconsFragment.input(mCommentExt, emojicon);
		
	}

}
